#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import sys
import traceback

from conf.configer import config
from logs.logger import logger
from mod.apkenc import ApkEncryptor, H5Encryptor
from mod.domain import DomainRepository

__VERSION__ = '2.1.0'

def main():
    try:
        logger.info('[+] ************************************************************')
        logger.info(f'[+] Kiwisec Commandline Frontend Tool v{__VERSION__}')
        logger.info('[+] ************************************************************')

        parser = argparse.ArgumentParser(add_help=False,prog='KiwiCli')

        # 基础配置
        parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS, help='查看帮助信息')
        parser.add_argument("--domain", dest='domain', type=str, help="配置API的目标域名")
        parser.add_argument("--show-domain", dest='show_domain', action='store_true', help="查看当前域名")
        parser.add_argument("--login", nargs=2, dest='login', metavar=('USERID', 'SECURITYKEY'),
                            type=str, help="首次使用必须先登录 <User ID> <Security Key>")
        parser.add_argument("-V", "--version", action='version', version=f'%(prog)s {__VERSION__}', help="查看当前KiwiCli版本")

        # Android 加固
        parser.add_argument("--show-tool-version", dest='show_tool_version', action='store_true', help="查看加固程序版本")
        parser.add_argument("--show-policy-list", dest='show_policy_list', action='store_true', help="查看加固策略列表")
        parser.add_argument("--search-policy-detail", nargs='+', dest='search_policy_detail', type=str, help="查看加固策略详情")

        parser.add_argument("--encrypt", nargs='+', dest='encrypt',
                            metavar=('INPUT_APK_PATH', 'OUTPUT_APK_PATH'),
                            type=str, help="加固命令 [APK路径] [输出路径] <加固策略ID> <加固程序版本>")

        # h5 加固
        parser.add_argument("--show-h5-policy-list", dest='show_h5_policy_list', action='store_true', help="查看加固策略列表")
        parser.add_argument("--search-h5-policy-detail", nargs='+', dest='search_h5_policy_detail', type=str,
                            help="查看加固策略详情")
        parser.add_argument("--h5-encrypt", nargs='+', dest='h5_encrypt',
                            metavar=('INPUT_ZIP_PATH', 'OUTPUT_ZIP_PATH'),
                            type=str, help="加固命令 [ZIP包路径] [输出路径] <加固策略ID>")
        args = parser.parse_args()
        logger.info(f'[+] {args}')

        if args.domain:
            DomainRepository().set('domain', args.domain)
            logger.info(f'[+] Set domain to {args.domain} ok')
            print(args.domain)

        if args.show_domain:
            domain = DomainRepository().get('domain')
            print(domain)

        if args.show_tool_version:
            tools = ApkEncryptor().webapi.get_toolShowVersion()
            for t in tools:
                print(t)

        if args.show_policy_list:
            policys = ApkEncryptor().webapi.get_encrypt_policys()
            for t in policys:
                print(t)

        if args.search_policy_detail:
            policy_id = args.search_policy_detail[0]
            print(policy_id)
            tactics = ApkEncryptor().webapi.get_encrypt_policy_detail(policy_id)
            for t in tactics:
                print(t)

        if args.login:
            config().set_cred(args.login[0], args.login[1])
            logger.info(f'[+] Set login credential ok')

        if args.encrypt:
            pid = toolver = ''
            apkin, apkout = args.encrypt[0], args.encrypt[1]
            nargs = len(args.encrypt)
            if nargs >= 3:
                pid = args.encrypt[2]
            if nargs >= 4:
                toolver = args.encrypt[3]
            encryptor = ApkEncryptor(apkin, apkout, pid, toolver)
            encryptor.run()

        # h5加固
        if args.show_h5_policy_list:
            policys = H5Encryptor().webapi.get_encrypt_policys()
            for t in policys:
                print(t)

        if args.search_h5_policy_detail:
            policy_id = args.search_h5_policy_detail[0]
            print(policy_id)
            tactics = H5Encryptor().webapi.get_encrypt_policy_detail(policy_id)
            for t in tactics:
                print(t)

        if args.h5_encrypt:
            pid = ''
            apkin, apkout = args.h5_encrypt[0], args.h5_encrypt[1]
            nargs = len(args.h5_encrypt)
            if nargs >= 3:
                pid = args.h5_encrypt[2]
            encryptor = H5Encryptor(apkin, apkout, pid)
            encryptor.run()

    except Exception as e:
        logger.error(traceback.format_exc())
        sys.exit(e)
    return


if __name__ == '__main__':
    main()
